﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace Communication
{
    class UdpServer : IServer
    {
        private readonly IRequestHandler handler;

		private readonly Socket listenerSocket;

        public UdpServer(IRequestHandler handler, IPEndPoint endPoint)
        {
            this.handler = handler;
            listenerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            listenerSocket.Bind(endPoint);
        }

        public UdpServer(IRequestHandler handler, IPAddress ip, int port)
			: this (handler, new IPEndPoint(ip, port)) { }

        public void StartAsync()
        {
            new Thread(Start).Start();
        }

        public void Stop()
        {
            listenerSocket.Close();
        }

        public void Dispose()
        {
            Stop();
        }

        public void Start()
        {
            listenerSocket.Listen(Int32.MaxValue);
			try
			{
				while (true)
				{
				    var client = listenerSocket.Accept();
					ThreadPool.QueueUserWorkItem(obj => HandleClient(client));
				}
			}
			catch (Exception error)
			{
				LogListenError(error);
			}
        }

        private void HandleClient(Socket client)
        {

            Stream clientStream = null;
            try
            {
                var request = ReadRequest(client);
                
                handler.Handle(new RequestContext(request, clientStream));
            }
            catch (Exception error)
            {
                LogError(error);
            }
            finally
            {
                client.Disconnect(true);
            }
        }

        private static MemoryStream ReadRequest(Socket client)
		{
            var buffer = new byte[4096];
            var request = new MemoryStream();
            int totalRead = 0;

            client.Receive(buffer, 0, sizeof(int), SocketFlags.Partial);

            int requestLength = BitConverter.ToInt32(buffer, 0);

            while (true)
            {
                if (totalRead >= requestLength)
                    break;
                int bytesRead = client.Receive(buffer, 0, Math.Min(buffer.Length, requestLength - totalRead), SocketFlags.Partial);
                if (bytesRead <= 0)
                    break;
                request.Write(buffer, 0, bytesRead);
                totalRead += bytesRead;
            }

            return request;
		}


        private void LogListenError(Exception error)
        {
            Console.Out.WriteLine("UdpServer. Error in accepting client: {0}", error);
        }

        private static void LogError(Exception error)
        {
            Console.Out.WriteLine("UdpServer. Error in processing request: {0}", error);
        }
    }
}
